package com.example.idlefish.GoodsInfo

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.media.Image
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.ActivityContract.ToChatContract
import com.example.idlefish.GoodsInfo.pojo.GoodEase
import com.example.idlefish.GoodsInfo.pojo.GoodForBrowse
import com.example.idlefish.GoodsInfo.pojo.Pair
import com.example.idlefish.GoodsInfo.pojo.QueryGoodContextResponse
import com.example.idlefish.GoodsInfo.pojo.SellerSoldInfo
import com.example.idlefish.HomeAndSearch.SearchActivity
import com.example.idlefish.Message.MessagePreviewData
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.contract.LoginContract
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.ApplicationConst.NetRequestForGoodContext
import com.example.idlefish.PublicModule.ApplicationConst.decodeBase64ToImage
import com.example.idlefish.PublicModule.ApplicationConst.server_ip
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import com.example.idlefish.databinding.ActivityGoodContentBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Period
import java.util.ArrayList
import kotlin.math.log


class GoodContentActivity : AppCompatActivity() {

    private lateinit var binding:ActivityGoodContentBinding
    private  var recommandList:ArrayList<GoodForBrowse> = arrayListOf()
    //List是不可变的r
    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }
    private val chatLauncher = registerForActivityResult(ToChatContract()){
        result->
    }
    private val goodMoreLauncher = registerForActivityResult(GooddResultContract()){
            result->

    }
    private var isCollected:Int? = 0
    val bitmap1:Bitmap? = null
    private  var postList: ArrayList<SellerSoldInfo> = arrayListOf()
    private var goodId:Long = -1L
    private val userId = UserConst.id
    private  var  properties: MutableList<Pair<String, String>> = mutableListOf()
    private lateinit var adapter:propertyAdapter
    private lateinit var postListAdapter:postGoodAdapter
    private  var sellerId:Long? = null
    private var goodEase:GoodEase? = null
    private var sellerAvatar:String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityGoodContentBinding.inflate(layoutInflater)
        setContentView(binding.root)


       binding.loadingtv2.visibility = View.VISIBLE
        binding.loading2.show()


        val recyclerView:RecyclerView = findViewById(R.id.goodContentLstProperty)
        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding.goodContentLstProperty.layoutManager = layoutManager
        adapter = propertyAdapter(properties)
        binding.goodContentLstProperty.adapter = adapter

       val layoutManager1 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
       binding.lstPost.layoutManager = layoutManager1
        postListAdapter = postGoodAdapter(postList, applicationContext)
        binding.lstPost.adapter = postListAdapter

       /* val layoutManager2 = GridLayoutManager(this, 2)
       binding.lstRecommand.layoutManager = layoutManager2
       recommandAdapter = RecommandAdapter(recommandList, applicationContext)
       binding.lstRecommand.adapter = recommandAdapter */


        val drawable:Drawable = resources.getDrawable(R.drawable.property_divider)
        val dividerItemDecoration = DividerItemDecoration(
            recyclerView.context,
            layoutManager.getOrientation()
        )
        dividerItemDecoration.setDrawable(drawable)
        recyclerView.addItemDecoration(dividerItemDecoration)
        InitGoodContext()
        binding.goodContextReturn.setOnClickListener {
            val intent = Intent()
            setResult(RESULT_OK, intent)
            finish()
        }
       binding.iscollect.setOnClickListener {
           if(isCollected == 0)
           {
               isCollected = 1
               val num = binding.collect.text.toString().toInt()
               binding.collect.text = (num + 1).toString()
               binding.iscollect.setImageResource(R.drawable.collected)
               setCollectNet(isCollected!!, UserConst.id, goodId)
           }
           else
           {
               isCollected = 0
               val num = binding.collect.text.toString().toInt()
               binding.collect.text = (num - 1).toString()
               binding.iscollect.setImageResource(R.drawable.discollected)
               setCollectNet(isCollected!!, UserConst.id, goodId)
           }
       }
       binding.sellerAvater.setOnClickListener {
           sellerId?.let { it1 -> homepageLauncher.launch(it1) }
       }
       binding.sellerName.setOnClickListener{
           sellerId?.let { it1 -> homepageLauncher.launch(it1) }
       }
       binding.avatar2.setOnClickListener {
           homepageLauncher.launch(UserConst.id)
       }
       binding.name2.setOnClickListener {
           homepageLauncher.launch(UserConst.id)
       }
        binding.Search.setOnClickListener {
            val intent = Intent(applicationContext, SearchActivity::class.java)
            startActivity(intent)
        }
       binding.iwantit.setOnClickListener {

           if(goodEase != null) {
               val sellerAvatarr = binding.sellerAvater.drawable.toBitmap()
               val byteArrayOutputStream = ByteArrayOutputStream()
               sellerAvatarr.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
               val byteArray = byteArrayOutputStream.toByteArray()
               val base64String = Base64.encodeToString(byteArray, Base64.DEFAULT)
               val messagePreviewData = MessagePreviewData(
                       UserConst.id.toInt(),
                       sellerId!!.toInt(),
                   "",
                   base64String,
                       binding.sellerName.text.toString(),
                   base64String,
                   "",
                       "",
                       "",
                       0
                   )
               val pair = kotlin.Pair(goodEase!!, messagePreviewData!!)
               chatLauncher.launch(pair)
           }
       }
    }
    private class propertyViewHolder(view: View):ViewHolder(view){
        val property:TextView = view.findViewById(R.id.tvContextProperty)
        val propertyValue:TextView = view.findViewById(R.id.tvContextValue)
    }
    private class propertyAdapter(val lstProperty: List<Pair<String, String>>):Adapter<propertyViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): propertyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.property_layout, parent, false)
            val viewHolder = propertyViewHolder(view)
            return viewHolder
        }

        override fun getItemCount(): Int {
            return lstProperty.size
        }

        override fun onBindViewHolder(holder: propertyViewHolder, position: Int) {
            holder.property.text = lstProperty[position].first
            holder.propertyValue.text = lstProperty[position].second
        }
    }

    private class postGoodViewHolder(view:View):ViewHolder(view){
        val price:TextView = view.findViewById(R.id.postImagePrice)
        val postImage:ImageView = view.findViewById(R.id.postImage)
    }
    inner private class postGoodAdapter(val lstGood:ArrayList<SellerSoldInfo>, val context: Context):Adapter<postGoodViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): postGoodViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.post_good_layout, parent, false)
            val viewHolder = postGoodViewHolder(view)
            ////点击事件 跳转窗口
            viewHolder.itemView.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                goodMoreLauncher.launch(lstGood[index].goodId)
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: postGoodViewHolder, position: Int) {
            holder.price.text = "¥${lstGood[position].goodPrice}"
            val bitmap = decodeBase64ToImage(context, lstGood[position].goodPic)
            if (bitmap != null) {
                holder.postImage.setImageBitmap(bitmap)
                Log.e("postGoodAdapter", " 绑定成功position $position")

            } else {
                Log.e("postGoodAdapter", "Failed to decode image at position $position")
            }
        }

        override fun getItemCount(): Int {
            return lstGood.size
        }
    }
    private class RecommandViewHolder(view:View):ViewHolder(view){
        val rPic:ImageView = view.findViewById(R.id.rGoodImage)
        val rname:TextView = view.findViewById(R.id.rName)
        val rPrice:TextView = view.findViewById(R.id.rPrice)
        val rSellerAvatar:ImageView = view.findViewById(R.id.rSellerAvatar)
        val rWanting:TextView = view.findViewById(R.id.rWanting)
    }



        //这里写商品初始化
    fun InitGoodContext()
    {
        //val info = CommonUtil.getSerializable(this, "goodId", Long::class.java)
        goodId = intent.getLongExtra("goodId", -1L);
        if(goodId == -1L)
        {
            runOnUiThread {
                Toast.makeText(this, "intent传进来的是什么鬼东西", Toast.LENGTH_LONG).show()
            }
            binding.loadingtv2.visibility = View.GONE
            binding.loading2.hide()
        }
        else{
            NetRequestForGoodContext(goodId, object : Callback{
                override fun onFailure(call: Call, e: IOException) {
                    runOnUiThread {
                        Toast.makeText(applicationContext, "请求商品详情信息失败", Toast.LENGTH_LONG).show()
                        binding.loadingtv2.visibility = View.GONE
                        binding.loading2.hide()
                    }
                    e.printStackTrace()
                }

                @SuppressLint("SetTextI18n")
                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body?.string().toString()
                    val gson = Gson()
                    val ttype = object : TypeToken<QueryGoodContextResponse>(){}.type
                    val result:QueryGoodContextResponse =  gson.fromJson(responseData, ttype)

                    runOnUiThread {
                        val  querySellerResponse = result.querySellerResponse
                        val queryGoodResponse = result.queryGoodResponse
                        val sellerAvaterBitmap = decodeBase64ToImage(applicationContext, querySellerResponse.avatar63Code)
                        Log.i("returnGood", result.toString())
                        Log.i("sold", queryGoodResponse.sold.toString())
                        Log.i("用户详情信息{}",querySellerResponse.toString())
                        if(queryGoodResponse.sold == 0){
                            binding.goodContextPrice.text = queryGoodResponse.price.toString()
                            if(queryGoodResponse.postMethod != 1)
                            {
                                binding.goodContextPostMethod.text = "  "
                            }
                            binding.want.text = queryGoodResponse.want.toString().plus("想要")
                            binding.browse.text = queryGoodResponse.browse.toString().plus("浏览")
                            binding.goodContentDescrib.text = queryGoodResponse.info
                            //properties =  queryGoodResponse.Properties!!
                            properties.clear()
                            queryGoodResponse.Properties?.let { properties.addAll(it) }
                            Log.d("properties", properties.toString())
                            adapter.notifyDataSetChanged()
                            var pic1 : Bitmap? = null
                            val pic64BaseList = queryGoodResponse.picEncodeingList
                            if (pic64BaseList != null) {
                                if(pic64BaseList.size == 1)
                                {
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic1)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic11)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext,pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)

                                        }
                                    }
                                }
                                else if (pic64BaseList.size == 2) {
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic2)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic21, binding.pic22)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext,pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 3){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic3)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic31, binding.pic32, binding.pic33)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 4){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic4)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic41, binding.pic42, binding.pic43, binding.pic44)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 5){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic5)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic51, binding.pic52, binding.pic53, binding.pic54, binding.pic55)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 6){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic6)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic61, binding.pic62, binding.pic63, binding.pic64, binding.pic64, binding.pic66)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 7){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic7)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic71, binding.pic72, binding.pic73, binding.pic74, binding.pic75, binding.pic76, binding.pic77)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 8){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic8)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic81, binding.pic82, binding.pic83, binding.pic84, binding.pic85, binding.pic86, binding.pic87, binding.pic88)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                                else if(pic64BaseList.size == 9){
                                    val LinearLayout = findViewById<LinearLayout>(R.id.pic9)
                                    LinearLayout.visibility = View.VISIBLE
                                    val imageViews = mutableListOf(binding.pic91, binding.pic92, binding.pic93, binding.pic94, binding.pic95, binding.pic96, binding.pic97, binding.pic98, binding.pic99)
                                    for(i in pic64BaseList.indices){
                                        val bitmap = decodeBase64ToImage(applicationContext, pic64BaseList[i])
                                        if(i == 0)
                                        {
                                            pic1 = bitmap
                                        }
                                        if(bitmap != null){
                                            imageViews[i].setImageBitmap(bitmap)
                                        }
                                    }
                                }
                            }
                            //用户信息绑定
                            sellerId = querySellerResponse.id
                            binding.sellerAvater.setImageBitmap(sellerAvaterBitmap)
                            binding.sellerName.text = querySellerResponse.name
                            if(querySellerResponse.followed == 1){
                                binding.isfollow.text = "已关注"
                                binding.isfollow.setTextColor(ContextCompat.getColor(applicationContext,R.color.dangrey))
                            }
                            ApplicationConst.goodPic1 = pic1
                            goodEase = GoodEase(goodId, queryGoodResponse.price, queryGoodResponse.info?:"".substring(0, 10), queryGoodResponse.postPrice)
                        }
                        else{
                            Toast.makeText(applicationContext, "来晚了~宝贝已经卖出", Toast.LENGTH_LONG).show()
                            binding.soldGone1.visibility = View.GONE
                            binding.soldGone2.visibility = View.GONE
                            binding.dispear.visibility = View.VISIBLE
                        }
                        //页眉信息
                        binding.collect.text = (queryGoodResponse.collect?:0).toString()
                        if(queryGoodResponse.isCollected == 1)
                        {
                            isCollected = 1
                            binding.iscollect.setImageResource(R.drawable.collected)
                        }
                        else{
                            isCollected = 0
                            binding.iscollect.setImageResource(R.drawable.discollected)
                        }
                        //user商品
                        postList.clear()
                        if(querySellerResponse.postList?.isNotEmpty() == true) {
                            postList.addAll(querySellerResponse.postList.filterNotNull())
                            postListAdapter.notifyDataSetChanged()
                            Log.i("post商品列表{}", postList.toString())
                        }


                        binding.avatar2.setImageBitmap(sellerAvaterBitmap)
                        binding.name2.text = querySellerResponse.name
                        val now = LocalDate.now()
                        val dateString = querySellerResponse.date
                        val date = LocalDateTime.parse(dateString)
                        val datee = date.toLocalDate()
                        val period = Period.between(datee, now)
                        val year = period.years
                        val months = period.months
                        val days = period.days
                        val soldNum = querySellerResponse.soldNum
                        if(year > 0)
                        {
                            binding.descibe.text = "来咸鱼${year}年,共卖出${soldNum}件宝贝"
                        }
                        else if(months > 0)
                        {
                            binding.descibe.text = "来咸鱼${months}月,共卖出${soldNum}件宝贝"
                        }
                        else
                        {
                            binding.descibe.text = "来咸鱼${days}月,共卖出${soldNum}件宝贝"
                        }
                        binding.loadingtv2.visibility = View.GONE
                        binding.loading2.hide()
                    }
                }
            })
        }
    }
    //返回商品详情页的所有信息封装
    fun setCollectNet( isCollect:Int, userId:Long, goodId:Long)
    {
        val client = OkHttpClient()
        val jsp = "http://${server_ip}:8080/user/setCollect?isCollect=${isCollect}&userId=${userId}&goodId=${goodId}"
        val request = Request.Builder()
            .url(jsp).get().build()
        client.newCall(request).enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.i("collect", "收藏操作失败")
            }

            override fun onResponse(call: Call, response: Response) {
                Log.i("collect", "收藏操作成功")
            }
        })
    }

}